package com.weifly.weistock.core.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 独立线程的更新服务
 *
 * @author weifly
 * @since 2019/2/3
 */
public class ThreadUpdateService extends AbstractUpdateService {

    private Logger logger = LoggerFactory.getLogger(ThreadUpdateService.class);

    private boolean isRun = false;
    private Object lock = new Object();
    private Thread updateThread;

    private String threadName = "stockUpdateThread"; // 线程名称
    private UpdateTask[] updateTasks; // 任务集合

    /**
     * 启动更新线程
     */
    public void startUpdateEveryTime(){
        synchronized (this.lock){
            if(this.isRun){
                logger.warn("already run!");
                return;
            }
            this.isRun = true;

            String threadName = this.getThreadName();
            this.updateThread = new Thread(new Runnable() {
                public void run() {
                    runInThread();
                }
            }, threadName);
            this.updateThread.start();
        }
    }

    /**
     * 重置状态，并唤醒线程
     */
    public void resetStatus(){
        synchronized (this.lock){
            super.resetStatus();
            this.lock.notifyAll();
        }
    }

    private void runInThread(){
        while(true){
            synchronized (this.lock){
                if(!this.isRun){
                    break;
                }
            }

            UpdateStatus updateStatus = null;
            try{
                // 检查
                synchronized (this.lock){
                    updateStatus = checkStatus();
                }

                // 执行
                if(this.updateTasks!=null && this.updateTasks.length>0){
                    for(UpdateTask task : this.updateTasks){
                        task.doRunTask(updateStatus);
                    }
                }
            }catch(Throwable e){
                logger.error("执行失败", e);
            }finally{
                try {
                    long sleepTime = updateStatus==null ? 3000 : updateStatus.getSleepTime();
                    synchronized (this.lock){
                        this.lock.wait(sleepTime);
                    }
                } catch (InterruptedException e) {
                    logger.error("中断", e);
                }
            }
        }
    }

    public String getThreadName() {
        return threadName;
    }

    public void setThreadName(String threadName) {
        this.threadName = threadName;
    }

    public UpdateTask[] getUpdateTasks() {
        return updateTasks;
    }

    public void setUpdateTasks(UpdateTask[] updateTasks) {
        this.updateTasks = updateTasks;
    }
}
